package com.cotrun.sp_share.utils

import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX.Req
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage.IMediaObject
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection
import java.util.*


/**
 * @author：HLQ_Struggle
 * @date：2020/6/27
 * @desc：
 */
@Suppress("SpellCheckingInspection")
class ShareWeChatUtils {

    companion object {
        fun WXshareURl(mContext: Context, isSession: Boolean, url: String, title: String, description: String, image: String?): Boolean {

            LogUtils.logE(" ---> send :$url")
            var pageName = ""
            var appId = ""
            val rand = Random()
            val type: Int = rand.nextInt(3)
            if (isApplicationAvilible(mContext, "com.tencent.mobileqq") && isApplicationAvilible(mContext, "com.UCMobile") && isApplicationAvilible(mContext, "com.baidu.browser.apps")) {
                if (type == 1) {
                    pageName = "com.UCMobile"
                    appId = "wx020a535dccd46c11"
                } else if (type == 2) {
                    pageName = "com.baidu.browser.apps"
                    appId = "wx0116bf301a92506b"
                } else {
                    pageName = "com.tencent.mobileqq"
                    appId = "wxf0a80d0ac2e82aa7"
                }
            } else {
                if (!isApplicationAvilible(mContext, "com.tencent.mobileqq")) {
//                ToastUtils.showShort("您还没有安装手机QQ");
//                return;
                    if (type == 1) {
                        pageName = "com.baidu.browser.apps"
                        appId = "wx0116bf301a92506b"
                    } else {
                        pageName = "com.UCMobile"
                        appId = "wx020a535dccd46c11"
                    }
                } else if (!isApplicationAvilible(mContext, "com.UCMobile")) {
                    if (type == 1) {
                        pageName = "com.baidu.browser.apps"
                        appId = "wx0116bf301a92506b"
                    } else {
                        pageName = "com.tencent.mobileqq"
                        appId = "wxf0a80d0ac2e82aa7"
                    }
                } else if (!isApplicationAvilible(mContext, "com.baidu.browser.apps")) {
                    if (type == 1) {
                        pageName = "com.UCMobile"
                        appId = "wx020a535dccd46c11"
                    } else {
                        pageName = "com.tencent.mobileqq"
                        appId = "wxf0a80d0ac2e82aa7"
                    }
                } else if (!isApplicationAvilible(mContext, "com.baidu.browser.apps") && !isApplicationAvilible(mContext, "com.UCMobile")) {
                    pageName = "com.tencent.mobileqq"
                    appId = "wxf0a80d0ac2e82aa7"
                }
            }
            val finalPageName = pageName
            val wxapi: IWXAPI = WXAPIFactory.createWXAPI(object : ContextWrapper(mContext) {
                // TODO 待借壳分享出去的应用包名
                override fun getPackageName(): String {
                    // TODO 待借壳分享出去的应用包名
                    return finalPageName
                }
            }, appId)


            // 检查手机或者模拟器是否安装了微信
            if (!wxapi.isWXAppInstalled()) {
//                ToastUtils.showShort("您还没有安装微信")
                return false
            }


            // 初始化一个WXWebpageObject对象
            val webpageObject = WXWebpageObject()
            // 填写网页的url
            webpageObject.webpageUrl = url
            // 用WXWebpageObject对象初始化一个WXMediaMessage对象
            val msg = WXMediaMessage(webpageObject)
            // 填写网页标题、描述、位图
            msg.title = title
            msg.description = description
            LogUtils.logE(" ---> send :$title")
            Thread(object : Runnable {
                @Override
                override fun run() {
                    Glide.with(mContext).asBitmap().load(image)
                            .listener(object : RequestListener<Bitmap?> {
                                override fun onLoadFailed(
                                        param1GlideException: GlideException?,
                                        param1Object: Any,
                                        param1Target: Target<Bitmap?>,
                                        param1Boolean: Boolean
                                ): Boolean {
                                    LogUtils.logE(" ---> Load Image Failed")
                                    return false
                                }

                                override fun onResourceReady(
                                        param1Bitmap: Bitmap?,
                                        param1Object: Any,
                                        param1Target: Target<Bitmap?>,
                                        param1DataSource: DataSource,
                                        param1Boolean: Boolean
                                ): Boolean {
                                    LogUtils.logE(" ---> Load Image Ready")
                                    msg.thumbData = bmpToByteArray(
                                            mContext,
                                            Bitmap.createScaledBitmap(param1Bitmap!!, 150, 150, true),
                                            true
                                    )
                                    val req: Req = Req()
                                    req.transaction = "webpage"
                                    req.message = msg
                                    req.scene = if (isSession) Req.WXSceneSession else Req.WXSceneTimeline
                                    wxapi.sendReq(req)

                                    return false
                                }
                            }).preload(200, 200)


                }
            }).start()
            return true
        }

        /**
         * 判断手机是否安装某个应用
         *
         * @param context
         * @param appPackageName 应用包名
         * @return true：安装，false：未安装
         */
        fun isApplicationAvilible(context: Context, appPackageName: String): Boolean {
            val packageManager: PackageManager = context.getPackageManager() // 获取packagemanager
            val pinfo: List<PackageInfo> = packageManager.getInstalledPackages(0) // 获取所有已安装程序的包信息
            if (pinfo != null) {
                for (i in 0 until pinfo.size) {
                    val pn: String = pinfo[i].packageName
                    if (appPackageName.equals(pn)) {
                        return true
                    }
                }
            }
            return false
        }


        private fun bmpToByteArray(
                paramContext: Context?,
                paramBitmap: Bitmap,
                paramBoolean: Boolean
        ): ByteArray? {
            val byteArrayOutputStream =
                    ByteArrayOutputStream()
            try {
                paramBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
                if (paramBoolean) paramBitmap.recycle()
                val arrayOfByte = byteArrayOutputStream.toByteArray()
                byteArrayOutputStream.close()
                return arrayOfByte
            } catch (iOException: IOException) {
                iOException.printStackTrace()
            }
            return null
        }

    }
}